import cookies from "./util.cookies";
import db from "./util.db";
import log from "./util.log";
import { resolve } from "q";

const util = {
  cookies,
  db,
  log
};

/**
 * @description 更新标题
 * @param {String} title 标题
 */
util.title = function(titleText) {
  const processTitle = process.env.VUE_APP_TITLE || "D2Admin";
  window.document.title = `${processTitle}${
    titleText ? ` | ${titleText}` : ""
  }`;
};

/**
 * @description 打开新页面
 * @param {String} url 地址
 */
util.open = function(url) {
  var a = document.createElement("a");
  a.setAttribute("href", url);
  a.setAttribute("target", "_blank");
  a.setAttribute("id", "d2admin-link-temp");
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(document.getElementById("d2admin-link-temp"));
};

/**
 * 一键粘贴
 * @param  {String} id [需要粘贴的内容]
 * @param  {String} attr [需要 copy 的属性，默认是 innerText，主要用途例如赋值 a 标签上的 href 链接]
 *
 * range + selection
 *
 * 1.创建一个 range
 * 2.把内容放入 range
 * 3.把 range 放入 selection
 *
 * 注意：参数 attr 不能是自定义属性
 * 注意：对于 user-select: none 的元素无效
 * 注意：当 id 为 false 且 attr 不会空，会直接复制 attr 的内容
 */
util.copy = function(id, attr) {
  const promiss = new Promise((resolve, reject) => {
    let target = null;

    if (attr) {
      target = document.createElement("div");
      target.id = "tempTarget";
      target.style.opacity = "0";
      if (id) {
        let curNode = document.querySelector("#" + id);
        target.innerText = curNode[attr];
      } else {
        target.innerText = attr;
      }
      document.body.appendChild(target);
    } else {
      target = document.querySelector("#" + id);
    }

    try {
      let range = document.createRange();
      range.selectNode(target);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);
      document.execCommand("copy");
      window.getSelection().removeAllRanges();
      resolve();
    } catch (e) {
      reject();
    }

    if (attr) {
      // remove temp target
      target.parentElement.removeChild(target);
    }
  });

  return promiss;
};

util.getServerUrl = function(api) {
  return process.env.VUE_APP_API + api;
};

util.getQueryString = function(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
};

export default util;
